<?php
namespace Api\Controller;

use Api\Controller\BaseController;
use Lib\WXMicro\WXSession;
use Lib\WXMicro\WXBizDataCrypt;
use Lib\WXMicro\ErrorCode;
use Think\Crypt;
use Think\Log;
use Lib\Aliyun\Sms\Sms;

/**
 * 经纪人
 *
 * @author ryan
 *        
 */
class BrokerController extends BaseController
{

    /**
     * 微信预登录
     */
    public function wxLogin()
    {
        $code = $this->_data['code']; // I('code');
        $encryptedData = $this->_data['encryptedData'];
        $iv = $this->_data['iv']; // I('iv');
        $appid = C('MICRO_APPID');
        $appscrect = C('MICRO_APPSECRET');
        if (empty($code)) {
            $this->result(1000, array(), 'js_code为空');
        }
        $session = new WXSession($appid, $appscrect);
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appscrect}&js_code={$code}&grant_type=authorization_code";
        $result = $session->getSessionKey($url);
        if (empty($result) || ! isset($result['session_key'])) {
            $this->result(1001, array(), 'session_key获取失败');
        }
        if (! isset($result['openid'])) {
            $this->result(1002, array(), '授权失败');
        }
        $data = array();
        $wxbizData = new WXBizDataCrypt($appid, $result['session_key']);
        $errcode = $wxbizData->decryptData(urldecode($encryptedData), urldecode($iv), $data);
        if ($errcode === ErrorCode::$OK) {
            $open_id = $result['openid'];
            if (isset($result['unionid'])) {
                $unionid = $result['unionid'];
            }
            $broker = D('Broker')->where(array(
                'wx_openid' => $open_id
            ))->find();
            $res = array();
            if (empty($broker)) {
                $info = array();
                $info['nickname'] = $data['nickName'];
                $info['wx_openid'] = $open_id;
                $info['wx_unionid'] = empty($unionid) ? '' : $unionid;
                $info['wx_info'] = Crypt::encrypt($data, $open_id);
                $info['is_bind_wechat'] = 1;
                $info['avatar_url'] = empty($data['avatarUrl']) ? '' : $data['avatarUrl'];
                $info['add_time'] = TIMESTAMP;
                $broker_id = D('Broker')->add($info);
                if ($broker_id === false) {
                    $this->result(1003, array(), '登录失败[添加用户失败]');
                }
                $res['avatar_url'] = $data['avatarUrl'];
                $res['nickname'] = $data['nickName'];
                $res['invite_code'] = '';
                $res['broker_time'] = 0;
                $res['is_active'] = 0;
                $res['openid'] = $open_id;
                $res['status'] = 0;
            } else {
                $res['avatar_url'] = $broker['avatar_url'];
                $res['nickname'] = $broker['nickname'];
                $res['invite_code'] = $broker['active_code'];
                $res['broker_time'] = $broker['broker_time'];
                $res['is_active'] = $broker['is_active'];
                $res['open_id'] = $broker['wx_openid'];
                $res['status'] = $broker['status'];
                $broker_id = $broker['id'];
            }
            $token = array();
            $token['broker_id'] = $broker_id;
            $token['add_time'] = TIMESTAMP;
            $token['status'] = 0;
            $token['token'] = md5($broker_id . $token['add_time']);
            $status = D('BrokerToken')->add($token);
            if ($status === false) {
                $this->result(1004, array(), '登录失败[授权失败]');
            } else {
                $res['token'] = $token['token'];
                $this->result(0, $res, '登录成功');
            }
        } else {
            $this->result(1005, array(), '登录失败[解析失败]');
        }
    }

    /**
     * 微信openid登录
     */
    public function loginForOpenid()
    {
        $open_id = $this->_data['open_id'];
        if (empty($open_id)) {
            $this->result(1000, array(), '数据有误');
        }
        $broker = D('Broker')->where(array(
            'wx_openid' => $open_id
        ))->find();
        $res = array();
        if (empty($broker)) {
            $this->result(1003, array(), '用户不存在');
        }
        $res['avatar_url'] = $broker['avatar_url'];
        $res['nickname'] = $broker['nickname'];
        $res['invite_code'] = $broker['active_code'];
        $res['broker_time'] = $broker['broker_time'];
        $res['is_active'] = $broker['is_active'];
        $res['open_id'] = $broker['wx_openid'];
        $res['status'] = $broker['status'];
        $broker_id = $broker['id'];
        $token = array();
        $token['broker_id'] = $broker_id;
        $token['add_time'] = TIMESTAMP;
        $token['status'] = 0;
        $token['token'] = md5($broker_id . $token['add_time']);
        $status = D('BrokerToken')->add($token);
        if ($status === false) {
            $this->result(1004, array(), '登录失败[授权失败]');
        } else {
            $res['token'] = $token['token'];
            $this->result(0, $res, '登录成功');
        }
    }

    /**
     * 手机登录
     */
    public function mobileLogin()
    {}

    /**
     * 经纪人激活
     */
    public function brokerActive()
    {
        $token = $this->_data['token'];
        $mobile = $this->_data['mobile'];
        $code = $this->_data['code'];
        $inviter_code = $this->_data['invite_code'];
        if (empty($mobile)) {
            $this->result(1000, array(), '手机号不又能为空');
        }
        if (! preg_match("/^1[34578]{1}\d{9}$/", $mobile)) {
            $this->result(1000, array(), '请输入正确的手机号');
        }
        if (empty($code)) {
            $this->result(1000, array(), '验证码不能为空');
        }
        if (empty($inviter_code)) {
            $this->result(1000, array(), '激活码不能为空');
        }
        if (empty($token)) {
            $this->result(2000, array(), '无权限访问');
        }
        $broker = D('Broker')->where(array(
            'mobile' => $mobile
        ))->find();
        if (! empty($broker)) {
            $this->result(1000, array(), '该手机已经绑定过了');
        }
        $brokerToken = D('BrokerToken')->where(array(
            'token' => $token
        ))->find();
        if (empty($brokerToken)) {
            $this->result(2001, array(), '无权限访问');
        }
        $brokerCode = D('BrokerCode')->where(array(
            'mobile' => $mobile,
            'code' => $code
        ))->find();
        if (! empty($brokerCode) && $brokerCode['status'] == 0) {
            $timediff = TIMESTAMP - $brokerCode['add_time'];
            if (floor($timediff / 60) > 5) {
                $this->result(1000, array(), '短信验证码已超时');
            }
        } else {
            $this->result(1000, array(), '无效验证码');
        }
        $inviter = D('Broker')->where(array(
            'invite_code' => $inviter_code
        ))->find();
        if (empty($inviter)) {
            // $this->result(1000, array(), '无效激活码');
        }
        $data = array();
        $data['mobile'] = $mobile;
        $data['is_bind_mobile'] = 1;
        $data['recommend_code'] = $inviter_code;
        $data['status'] = 10; // 待审核
        D()->startTrans();
        $update = D('BrokerCode')->where(array(
            'id' => $brokerCode['id']
        ))->save(array(
            'status' => 1
        ));
        if ($update === false) {
            $this->result(1000, array(), '验证失败');
        }
        $status = D('Broker')->where(array(
            'id' => $brokerToken['broker_id']
        ))->save($data);
        if ($status === false) {
            D()->rollback();
            $this->result(1000, array(), '验证失败');
        } else {
            D()->commit();
            $this->result();
        }
    }

    /**
     * 验证码
     */
    public function brokerCode()
    {
        $token = $this->_data['token'];
        $mobile = $this->_data['mobile'];
        if (empty($mobile)) {
            $this->result(1000, array(), '手机号不又能为空');
        }
        if (! preg_match("/^1[34578]{1}\d{9}$/", $mobile)) {
            $this->result(1000, array(), '请输入正确的手机号');
        }
        if (empty($token)) {
            $this->result(2000, array(), '无权限访问');
        }
        $brokerToken = D('BrokerToken')->where(array(
            'token' => $token
        ))->find();
        if (empty($brokerToken)) {
            $this->result(2001, array(), '无权限访问');
        }
        $broker = D('Broker')->where(array(
            'mobile' => $mobile
        ))->find();
        if (! empty($broker)) {
            $this->result(2001, array(), '该手机号已绑定过');
        }
        $code = rand(1000, 9999);
        D()->startTrans();
        $data = array();
        $data['code'] = $code;
        $data['mobile'] = $mobile;
        $data['add_time'] = TIMESTAMP;
        $data['status'] = 0;
        $status = D('BrokerCode')->add($data);
        if ($status === false) {
            $this->result(1000, array(), '验证码生成失败');
        }
        $response = Sms::sendSms($mobile, '金库', 'SMS_134120080', array(
            'code' => $code
        ));
        Log::record(serialize($response));
        if ($response['Code'] === 'OK') {
            D()->commit();
            $this->result();
        } else {
            D()->rollback();
            $this->result(1000, array(), '验证码发送失败');
        }
    }

    /**
     * 需求列表
     */
    public function demandList()
    {
        $token = $this->_data['token'];
        $type = $this->_data['type'];
        $page = $this->_data['page'];
        $limit = $this->_data['limit'];
        if (empty($token)) {
            $this->result(2000, array(), '无权限访问');
        }
        $broker = D('BrokerToken')->where(array(
            'token' => $token
        ))->find();
        if (empty($broker)) {
            $this->result(2001, array(), '无权限访问');
        }
        $demands = D('Demand')->where(array(
            'status' => 12
        ))
            ->page($page, $limit)
            ->order('add_time desc')
            ->select();
        $data = array();
        $data['list'] = $demands;
        $data['page'] = $page + 1;
        $data['count'] = count($demands);
        $this->result(0, $data);
    }

    /**
     * 资金列表
     */
    public function capitalList()
    {
        $token = $this->_data['token'];
        $type = $this->_data['type'];
        $page = $this->_data['page'];
        $limit = $this->_data['limit'];
        if (empty($token)) {
            $this->result(2000, array(), '无权限访问');
        }
        $broker = D('BrokerToken')->where(array(
            'token' => $token
        ))->find();
        if (empty($broker)) {
            $this->result(2001, array(), '无权限访问');
        }
        $capitals = D('Capital')->where(array(
            'status' => 12
        ))
            ->field('capital_sn,capital_amount,capital_demand_type,add_time')
            ->order('add_time desc')
            ->page($page, $limit)
            ->select();
        $data = array();
        $data['list'] = $capitals;
        $data['page'] = $page + 1;
        $data['count'] = count($capitals);
        $this->result(0, $data);
    }

    /**
     * 获取资金信息
     */
    public function getCapitalDetail()
    {
        if ($this->checkToken()) {
            $sn = $this->_data['sn'];
            $capital = D('Capital')->where(array(
                'capital_sn' => $sn
            ))
                ->relation('attachs')
                ->field('id,capital_sn,capital_amount,capital_demand_type,capital_source,capital_type,add_time')
                ->find();
            if (! empty($capital)) {
                $demands = D('Demand')->where(array(
                    'intention_capital' => $capital['id']
                ))
                    ->field('demand_sn,demand_amount,demand_date,add_time,intention_capital,province,city,status,demand_day')
                    ->relation(true)
                    ->select();
                $capital['demands'] = $demands;
            }
            $this->result(0, $capital);
        }
    }

    /**
     * 添加项目
     */
    public function addDemandForCapital()
    {
        $broker = $this->checkToken();
        if (! empty($broker)) {
            $info = $this->_data['info'];
            $data = array();
            if (empty($info['requestMoney'])) {
                $this->result(3000, array(), '需求金额不为能空');
            }
            $data['demand_sn'] = getSN('DS');
            $data['demand_type'] = $info['requestType'];
            $data['province'] = $info['province'];
            $data['city'] = $info['city'];
            $data['demand_amount'] = floatval($info['requestMoney']) * 10000.00;
            $data['demand_date'] = $info['requestDate'];
            $data['demand_day'] = $info['requestDay'];
            $data['business_name'] = $info['businessName'];
            $data['tel'] = $info['requestMobile'];
            $data['contacts'] = $info['requestContact'];
            $data['business_nature'] = empty($info['natureType']) ? 0 : $info['natureType'];
            $data['custom_type'] = $info['customType'];
            $data['demand_member_type'] = 1;
            $data['member_id'] = $broker['id'];
            $data['intention_capital'] = $info['capital_id'];
            $data['add_time'] = TIMESTAMP;
            D()->startTrans();
            $demand_id = D('Demand')->add($data);
            if ($demand_id === false) {
                D()->rollback();
                $this->result(3000, array(), '提交项目失败');
            }
            $record = array();
            $record['demand_id'] = $demand_id;
            $record['status'] = 0;
            $record['remark'] = '提交成功待审核';
            $record['add_time'] = TIMESTAMP;
            $status = D('DemandRecord')->add($record);
            if ($status === false) {
                D()->rollback();
                $this->result(3000, array(), '提交需求失败');
            } else {
                D()->commit();
                $this->result();
            }
        }
    }

    /**
     * 经纪人项目列表
     */
    public function brokerDemand()
    {
        $token = $this->_data['token'];
        $type = $this->_data['type'];
        $page = $this->_data['page'];
        $limit = $this->_data['limit'];
        if (empty($token)) {
            $this->result(2000, array(), '无权限访问');
        }
        $broker = D('BrokerToken')->where(array(
            'token' => $token
        ))->find();
        if (empty($broker)) {
            $this->result(2001, array(), '无权限访问');
        }
        $condition = array();
        $condition['demand_member_type'] = 1;
        $condition['member_id'] = $broker['broker_id'];
        $demands = D('Demand')->where($condition)
            ->relation(true)
            ->field('business_nature,business_name,custom_type,demand_amount,demand_date,demand_day,demand_member_type,demand_sn,demand_type,status,province,city')
            ->page($page, $limit)
            ->order('add_time desc')
            ->select();
        $data = array();
        $data['list'] = $demands;
        $data['page'] = $page + 1;
        $data['count'] = count($demands);
        $this->result(0, $data);
    }

    /**
     * 发布需求
     */
    public function releaseBrokerDemand()
    {
        $info = $this->_data['info'];
        $token = $this->_data['token'];
        if (empty($token)) {
            $this->result(1000, array(), '无权限访问');
        }
        $broker = D('BrokerToken')->relation(true)
            ->where(array(
            'token' => $token
        ))
            ->find();
        if (empty($broker)) {
            $this->result(2001, array(), '无权限访问');
        }
        if ($broker['broker']['is_active'] == 0 || $broker['broker']['broker_time'] < TIMESTAMP) {
            $this->result(2001, array(), '账号未激活');
        }
        $data = array();
        if (empty($info['requestMoney'])) {
            $this->result(3000, array(), '需求金额不为能空');
        }
        $data['demand_sn'] = getSN('DS');
        $data['demand_type'] = $info['requestType'];
        $data['province'] = $info['province'];
        $data['city'] = $info['city'];
        $data['demand_amount'] = floatval($info['requestMoney']) * 10000.00;
        $data['demand_date'] = $info['requestDate'];
        $data['demand_day'] = $info['requestDay'];
        $data['business_name'] = $info['businessName'];
        $data['tel'] = $info['requestMobile'];
        $data['contacts'] = $info['requestContact'];
        $data['business_nature'] = empty($info['natureType']) ? 0 : $info['natureType'];
        $data['custom_type'] = $info['customType'];
        $data['demand_member_type'] = 1;
        $data['member_id'] = $broker['broker']['id'];
        $data['add_time'] = TIMESTAMP;
        D()->startTrans();
        $demand_id = D('Demand')->add($data);
        if ($demand_id === false) {
            D()->rollback();
            $this->result(3000, array(), '发布需求失败');
        }
        $record = array();
        $record['demand_id'] = $demand_id;
        $record['status'] = 0;
        $record['remark'] = '发布成功待审核';
        $record['add_time'] = TIMESTAMP;
        $status = D('DemandRecord')->add($record);
        if ($status === false) {
            D()->rollback();
            $this->result(3000, array(), '发布需求失败');
        } else {
            D()->commit();
            $this->result();
        }
    }

    /**
     * 订单列表
     */
    public function brokerOrder()
    {}

    /**
     * 订单详情
     */
    public function brokerOrderDetail()
    {}

    /**
     * 我的合伙人
     */
    public function myPartners()
    {
        $broker = $this->checkToken();
        if (! empty($broker)) {
            $page = $this->_data['page'];
            $limit = $this->_data['limit'];
            $condition = array();
            $condition['recommend_code'] = $broker['active_code'];
            $partners = D('Broker')->where($condition)
                ->relation(true)
                ->page($page, $limit)
                ->field('avatar_url,nickname,add_time')
                ->order('add_time desc')
                ->select();
            $count = D('Broker')->where($condition)->count();
            $data = array();
            $data['list'] = $partners;
            $data['page'] = $page + 1;
            $data['count'] = $count;
            $this->result(0, $data);
        }
    }

    /**
     * 修改经纪人信息
     */
    public function editBrokerInfo()
    {}

    /**
     * 获取经纪人信息
     */
    public function getBrokerInfo()
    {
        $token = $this->_data['token'];
        if (empty($token)) {
            $this->result(1000, array(), '无权限操作');
        }
        $brokerToken = D('BrokerToken')->where(array(
            'token' => $token
        ))->find();
        if (empty($brokerToken)) {
            $this->result(1000, array(), '无权限操作');
        }
        $broker = D('Broker')->where(array(
            'id' => $brokerToken['broker_id']
        ))->find();
        $res = array();
        if (empty($broker)) {
            $this->result(1003, array(), '用户不存在');
        }
        $res['avatar_url'] = $broker['avatar_url'];
        $res['nickname'] = $broker['nickname'];
        $res['invite_code'] = $broker['active_code'];
        $res['broker_time'] = $broker['broker_time'];
        $res['is_active'] = $broker['is_active'];
        $res['status'] = $broker['status'];
        $this->result(0, $res);
    }

    /**
     * 认证身份信息
     */
    public function verifyBrokerInfo()
    {}

    /**
     * 审核经纪人
     */
    public function auditingBroker()
    {}

    /**
     * 待审核经纪人
     */
    public function unauditedBroker()
    {}
}

